package org.jspresso.framework.application.frontend.action;

import java.util.Map;

import org.jspresso.framework.action.IAction;
import org.jspresso.framework.action.IActionHandler;
import org.jspresso.model.ActionTestInput;
import org.jspresso.model.ActionTestIo;
import org.jspresso.model.BackActionTest;
import org.jspresso.model.Voyage;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class BackActionTestFrontAction<E,F,G> extends FrontendAction<E,F,G> implements ApplicationContextAware {

	ApplicationContext applicationContext;

	@Override
	public boolean execute(IActionHandler actionHandler, Map<String, Object> context) {

		BackActionTest backAction = getSelectedModel(context);
		if(backAction != null) {

			Object backendAction = applicationContext.getBean(backAction.getBackendBeanName());

			if(backendAction != null && backendAction instanceof IAction) {
				for(ActionTestInput testInput : backAction.getInputs()) {
					Object inputValue = null;
					if(testInput.isSql()) {
						// Exec sql
					}
					else {
						switch(testInput.getParameterType()) {
						case ActionTestIo.PARAMETER_TYPE_REF:	inputValue = testInput.getParameterRefValue(); break;
						case ActionTestIo.PARAMETER_TYPE_LIST: 	inputValue = testInput.getParameterRefValues(); break;
						default: 								inputValue = testInput.getParameterScalarValue(); break;
						}
					}

					switch(testInput.getIoType()) {
					case ActionTestIo.IO_TYPE_ACTION_PARAMETER: setActionParameter(inputValue, context);
					case ActionTestIo.IO_TYPE_CONTEXT: context.put(ActionTestIo.PARAMETER_KEY, inputValue);
					}
				}

				actionHandler.execute((IAction) backendAction, context);
				
				System.out.println(((Voyage)getActionParameter(context)).getRef());;
			}
		}

		return super.execute(actionHandler, context);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;	
	}

}
